<?php

namespace App\Models\Ddaman;

use App\Models\xwbei\Student;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\common\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WorkflowFlow extends Base
{
    use HasFactory;

    protected $table = "workflow_flow";

    //const CREATED_AT = null;
    //const UPDATED_AT = null;

    protected $fillable = [
        'guid','title','design_id','step','description'
    ];


    public $rule = [
        'design_id' => 'required',
        'title' => 'required',
        'step' => 'required',
    ];

    public $editRule = [
        'guid' => 'required',
        'design_id' => 'required',
        'title' => 'required',
        'step' => 'required',
    ];

    public $message = [
        'guid.required' => '标识必须',
        'title.required' => '名称必须填写',
        'design_id.required'=>"设计标识必须",
        'step.required'=>"步骤必须",
        'step.unique'=>"步骤不能重复",
    ];

    /*
     * 获取列表
     * */
    public function getList( $param = [] )
    {
        $limit = isset($param['limit']) ? $param['limit'] : 10;

        $design_id = isset($param['design_id']) ? $param['design_id'] : null;
        $where = [
            'f.design_id'=>$design_id
        ];

        if (isset($param['keywords']) && $param['keywords']){
            $keywords = trim($param['keywords']);
            $where[] = ['f.title','like',"%$keywords%"];
        }

        /*$field = array_merge(['id'],$this->fillable);
        $list = $this->where($where)->orderBy('step','asc')->select($field)->paginate($limit);*/

        $list = DB::table('workflow_flow as f')
            ->leftJoin('workflow_flow_rule as r','f.guid','=','r.flow_id')
            ->select([
                'f.*','r.level','r.user_id','r.position_id','r.approve_type'
            ])
            ->where($where)
            ->get();

        return $list;

    }


    /*
     * 保存数据
     * */
    public function changes( $data , $rule)
    {
        $validator = Validator::make( $data ,$rule ,$this->message);
        if($validator->fails()){
            $this->error = $validator->errors()->toMsg();
            return false;
        }

        DB::beginTransaction();
        try {
            //同一步骤只允许一个
            $where = [
                'step'=>$data['step'],
                'design_id'=>$data['design_id']
            ];
            if (isset($data['guid']) && $data['guid']) {
                $guid = $data['guid'];
                $where[] = [function($query) use ($guid){
                    $query->whereNotIn('guid', [$guid]);
                }];
            }
            //dump($where);die;
            $info = $this->where($where)->first();
            if ($info){
                throw new \Exception('同一步骤不可重复提交');
            }

            if (isset($data['guid']) && $data['guid'])
            {
                $upData = stayFill($this->fillable,$data);
                //dump($upData);die;
                $result = WorkflowFlow::where('guid',$data['guid'])->update($upData);
                if (!$result){
                    throw new \Exception('编辑失败 1002');
                }
                $data['flow_id'] = $data['guid'];
            }else{
                $guid = getGuid();
                $data['guid'] = $guid;
                $result = WorkflowFlow::create($data);
                if (!$result){
                    throw new \Exception('新增失败 1001');
                }
                $data['flow_id'] = $guid;
            }

            //保存权限
            $result = $this->saveRule( $data );
            if (!$result){
                throw new \Exception($this->error);
            }

            DB::commit();
            return $result;
        }catch (\Exception $exception){
            DB::rollBack();
            $this->error = $exception->getMessage();
            return false;
        }
    }

    /*
     * 保存步骤权限
     * */
    public function saveRule( $data )
    {
        $rData = stayFill(WorkflowFlowRule::$fill,$data);
        if ($rData){
            $rData['flow_id'] = $data['flow_id'];
            $info = WorkflowFlowRule::where('flow_id',$data['flow_id'])->first();
            if ($info){
                $result = WorkflowFlowRule::where('id',$info->id)->update($rData);
            }else{
                $result = WorkflowFlowRule::create($rData);
            }
            if (!$result){
                $this->error = "更新失败 1003";
                return false;
            }
        }


        return true;
    }



}
